<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title>WebSocket测试</title>
</head>
<body>

<div id="sse">
    <a href="javascript:WebSocketTest();">测试浏览器是否支持WebSocket</a><br>
    <a href="javascript:WebSocketLink();">建立WebSocket连接</a><br>
    <input id="sendMsg" type="text"><a
        href="javascript:WebSocketSend(document.getElementById('sendMsg').value);">发送消息</a><br>
    <a href="javascript:WebSocketClose();">关闭WebSocket连接</a><br>
</div>
<script type="text/javascript">
    function WebSocketTest() {
        if ("WebSocket" in window) {
            alert("您的浏览器支持 WebSocket!");
        } else {
            alert("您的浏览器不支持 WebSocket!");
        }
    }

    var ws; //定义WebSocket对象
    function WebSocketLink() {
        if ("WebSocket" in window) {
            if (!ws || ws.readyState != 1) {
                ws = new WebSocket("ws://localhost:9998/echo"); // 打开一个 web socket
            } else {
                alert("已经连接了");
            }

            ws.onopen = function () { // 监听 Web Socket 已连接上
                alert("连接已打开...");
            };

            ws.onclose = function () { //监听 Web Socket 已关闭
                alert("连接已关闭...");
            };

            ws.onmessage = function (evt) { // 监听 Web Socket 收到消息
                console.log(evt);
                var received_msg = evt.data; //消息体
                alert("已接收：" + received_msg);
            };

        } else {
            // 浏览器不支持 WebSocket
            alert("您的浏览器不支持 WebSocket!");
        }
    }

    function WebSocketClose() { //关闭连接
        ws.close();
    }

    function WebSocketSend(msg) { //发送数据
        if (!ws) {
            alert("还没有建立WebSocket对象");
            return;
        }
        var status = ws.readyState;
        switch (status) {
            case 0:
                alert("连接尚未建立");
                break;
            case 1:
                // alert("连接已建立，可以进行通信");
                ws.send(msg);
                alert("已发送");
                break;
            case 2:
                alert("连接正在进行关闭");
                break;
            case 3:
                alert("连接已经关闭或者连接不能打开");
                break;
            default:
                alert("未知的错误发生了");
                break;
        }
    }
</script>
</body>
</html>